//
//  TextView+Emoticon.swift
//  表情键盘独立开发
//
//  Created by IOS on 15/8/14.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
extension UITextView {
    /// 插入表情符号
    ///
    /// :param: emoticon 表情符号
    func insertEmoticon(emoticon: Emoticon) {
        
        //删除文本
        if emoticon.removeEmoticon {
            deleteBackward()
            
            return
        }
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            
        }
        
        if emoticon.chs != nil {
            
            //创建图片属性字符串
            let attachment = EmoticonAttachment()
            attachment.chs = emoticon.chs
            
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
            //设置边界
            let h = font?.lineHeight
            print("线高\(h)")
            attachment.bounds = CGRect(x: 0, y: -4, width: h!, height: h!)
            
            let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            //添加文字属性
            imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            let attrString = NSMutableAttributedString(attributedString: attributedText)
            
            //插入图片文字
            attrString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            //使用可变属性文本替换文本视图的内容
            //记录光标位置
            let range = selectedRange
            //设置内容
            attributedText = attrString
            //恢复光标
            selectedRange = NSRange(location: range.location + 1, length: 0)
            
            delegate?.textViewDidChange!(self)
            
            
        }
    }
    
    // 对属性文本进行检测，并且拼接返回一个字符串
    /// 计算型属性，返回完整字符串
    var emoticonText: String {
        let attrString = attributedText
        
        var strM = String()
        attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("配图 \(attachment)")
                strM += attachment.chs!
                
            } else {
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        return strM
    }
    
}
